package utils

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"time"
)

// 初始化连接池配置
var httpTrans = &http.Transport{
	DialContext: (&net.Dialer{
		Timeout:   5 * 60 * time.Second,
		KeepAlive: 5 * 60 * time.Second,
	}).DialContext,
	ForceAttemptHTTP2:     true,
	MaxIdleConns:          100,                                     //所有Host的连接池最大空闲连接数
	MaxIdleConnsPerHost:   2,                                       //每个Host的连接池最大空闲连接数
	MaxConnsPerHost:       4,                                       //每个Host的连接池最大连接数
	IdleConnTimeout:       time.Duration(90000) * time.Millisecond, //空闲连接保留时间
	TLSHandshakeTimeout:   10 * time.Second,
	ExpectContinueTimeout: 1 * time.Second,
}

// 初始化连接池
var httpClient = &http.Client{
	Timeout:   5 * 60 * time.Second,
	Transport: httpTrans,
}

type CusHttp struct {
	Header map[string]string
}

// 发送GET请求
// url：         请求地址
func (cus *CusHttp) Get(url string) (out string, err error) {

	fmt.Printf("Response Url: %v \n", url)

	//初始化请求
	reqest, err := http.NewRequest("GET", url, nil)

	//增加Header选项
	if cus.Header != nil && len(cus.Header) > 0 {
		for k, vla := range cus.Header {
			reqest.Header.Add(k, vla)
		}
	}

	if err != nil {
		return "", err
	}

	resp, err := httpClient.Do(reqest)

	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	result, _ := io.ReadAll(resp.Body)
	fmt.Printf("Response Data:  %v \n\n", string(result))
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP request failed with status code: %v", resp.StatusCode)
	}
	return string(result), nil
}

// 发送POST请求 默认使用
// url：         请求地址
// data：        POST请求提交的数据
func (cus *CusHttp) Post(url string, data interface{}) (out string, err error) {
	return cus.post(url, data)
}

// 发送POST 表单
// url：         请求地址
// data：        POST请求提交的数据
func (cus *CusHttp) PostForm(url string, data interface{}) (out string, err error) {
	cus.Header["Content-Type"] = "application/x-www-form-urlencoded"
	return cus.post(url, data)
}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据
func (cus *CusHttp) post(url string, data interface{}) (out string, err error) {

	jsonStr, _ := json.Marshal(data)
	//初始化请求
	fmt.Println("\nResponse Body:", string(jsonStr))
	fmt.Printf("Response Url: %v \n", url)
	reqest, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	//增加Header选项
	if cus.Header != nil && len(cus.Header) > 0 {
		for k, vla := range cus.Header {
			reqest.Header.Add(k, vla)
		}
	}

	if err != nil {
		return "", err
	}

	resp, err := httpClient.Do(reqest)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	result, _ := io.ReadAll(resp.Body)
	fmt.Printf("Response Data:  %v \n\n", string(result))
	// 检查响应状态码是否为 200
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("HTTP request failed with status code: %v", resp.StatusCode)
	}
	return string(result), nil
}

// 发送POST请求
// url：         请求地址
// data：        POST请求提交的数据

// cusHttp := &utils.CusHttp{}
// imReq := loginReq{
// 	Username: "0086" + userData.Mobile,
// 	Password: config5.CFG.ImPassword,
// }
// resuit, err := cusHttp.Post(config5.CFG.ImLogin, imReq)
// if err != nil {
// 	return out, err
// }
// if err := json.Unmarshal([]byte(resuit), &out); err != nil {
// 	return out, err
// }
